<template>
  <div class="page">
    <div class="detail-header">
      {{projectDetail.name}}
    </div>
    <!-- 条件筛选 -->
    <div class="page_filter">
      <!--      <region-unit v-model="form.areaId" placeholder="选择监测对象对象"></region-unit>-->
      <el-input v-model="form.name" clearable placeholder="输入监测对象名称">
        <template slot="prepend">监测对象名称</template>
      </el-input>
      <el-select v-model.trim="form.monitorType" clearable placeholder="选择监测类型">
        <el-option v-for="item in EnumProjectMonitorTypeList" :key="item.code" :label="item.name"
                   :value="item.code"></el-option>
      </el-select>
      <el-select v-model.trim="form.warningLevel" clearable placeholder="选择预警等级">
        <el-option v-for="item in EnumWarningLevelList" :key="item.code" :label="item.name"
                   :value="item.code"></el-option>
      </el-select>
      <el-button class="common_btn-defalut" icon="el-icon-search" @click="queryList()">搜索</el-button>
    </div>
    <div class="page_main">
      <el-button icon="el-icon-plus" @click.stop="handleAdd" class="common_btn-small"
                 :disabled="hasPermission('project:workPoint:add')?false:'disabled'">监测对象新增
      </el-button>
      <el-button icon="el-icon-sort" @click.stop="handleSortWorkPoint" class="common_btn-small"
                 :disabled="!hasPermission('project:workPoint:update')">
        监测对象排序
      </el-button>
      <!-- table -->
      <el-table :data="tableList" border>
        <el-table-column label="序号" type="index" width="80">
        </el-table-column>
        <el-table-column prop="name" label="监测对象名称" min-width="220">
        </el-table-column>
        <el-table-column prop="area" label="所属行政区" min-width="160">
        </el-table-column>
        <el-table-column label="监测类型" min-width="220">
          <template slot-scope="scope">
            <el-button type="text" class="monitor-type" @click="toControl(item,scope.row.projectId)"
                       v-for="(item,index) in scope.row.monitorPointList" :key="item.id" size="small"
                       style="color: white">
              <i class="iconfont" :class="item.monitorType | gradeMonitorType"></i>
              {{item.monitorTypeName}}
              <span v-if="index != scope.row.monitorPointList.length - 1"> 、</span>
            </el-button>
          </template>
        </el-table-column>
        <el-table-column prop="scope.row.fxWarningPointList" label="最高预警等级" min-width="120">
          <template slot-scope="scope">
            <el-popover trigger="click" placement="right">
              <el-table border stripe
                        :data="scope.row.monitorWarningList"
                        style="width: 100%">
                <el-table-column prop="monitorTypeName" label="监测类型" width="180" class="TypeName">
                </el-table-column>
                <el-table-column label="预警等级" width="180">
                  <template slot-scope="scope">
                    <el-tag size="mini" :style="scope.row.warningLevel | gradeColor">{{scope.row.warningLevelName}}
                    </el-tag>
                  </template>
                </el-table-column>
              </el-table>
              <div slot="reference" class="name-wrapper" v-if="scope.row.monitorWarningList.length > 0">
                <el-button class="warning_button" size="mini" :style="scope.row.warningLevel | gradeColor">
                  {{scope.row.warningLevelName}}
                </el-button>
              </div>
            </el-popover>
          </template>
        </el-table-column>
        <el-table-column prop="remark" label="备注" show-overflow-tooltip min-width="80"></el-table-column>
        <el-table-column prop="createTime" width="170" label="更新时间">
          <template slot-scope="scope">
            {{scope.row.createTime | formatTimer }}
          </template>
        </el-table-column>
        <el-table-column prop="operator" label="操作人" min-width="80"></el-table-column>
        <el-table-column label="操作" fixed="right" min-width="240">
          <template slot-scope="scope">
            <el-button type="text" class="btn_edit"
                       :disabled="hasPermission('project:workPoint:update')?false:'disabled'"
                       @click="handleEdit(scope.row)">编辑
            </el-button>
            <el-button type="text" class="btn_add"
                       :disabled="hasPermission('project:workPoint:update')?false:'disabled'"
                       @click="handleAdd3d(scope.row)">3D模型
            </el-button>
            <el-button type="text" class="btn_delete"
                       :disabled="hasPermission('project:workPoint:delete')?false:'disabled'"
                       @click="handleDelete(scope.row)">删除
            </el-button>
            <el-button type="text" class="btn_add"
                       :disabled="hasPermission('project:workPoint:update')?false:'disabled'"
                       @click="handleControl(scope.row)">预警规则
            </el-button>
            <el-button type="text" class="btn_add"
                       :disabled="hasPermission('project:workPoint:update')?false:'disabled'"
                       @click="handleControlPhone(scope.row)">预警通知
            </el-button>
            <el-popover trigger="click" placement="right">
              <vue-qr :text="qrText" :margin="15" colorDark="#000" colorLight="#fff" style="height: 300px"></vue-qr>
              <div slot="reference" class="name-wrapper" style="display: inline">
                <button class="btn_test" @click="qrcode(scope.row.projectId+'?'+scope.row.id)" style="color: #1990FE">
                  二维码
                </button>
              </div>
            </el-popover>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页器 -->
      <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="form.page"
                     :page-size="form.pageSize" :page-sizes="[10, 20, 30, 40,50,60,70,80,90,100]"
                     layout="sizes, prev, pager, next" :total="total">
      </el-pagination>
    </div>
    <!-- 监测对象 新增编辑弹窗 -->
    <work-point-add-edit ref="workPoint" :slopeList="slopeList" :damageList="damageList" :bridgeList="bridgeList"
                         @update="reFlesh"></work-point-add-edit>
    <!-- 监测点 新增编辑弹窗  -->
    <monitor-point-add-edit
      @update="reFlesh"
      ref="monitorPoint">
    </monitor-point-add-edit>
    <el-drawer
      title="监测对象级别控制标准"
      :visible.sync="newForm"
      direction="rtl"
      custom-class="demo-drawer"
      ref="drawer"
      size="60%">
      <div class="demo-drawer__content">
        <warning-rules ref="warningRules" :workPointId="workPointId"></warning-rules>
      </div>
      <div class="demo-drawer__footer">
        <el-button type="primary" class=" common_btn-defalut" @click="newForm=false">确 定</el-button>
      </div>
    </el-drawer>
    <el-drawer
      title="预警推送"
      :visible.sync="newFormPhone"
      direction="rtl"
      custom-class="demo-drawer"
      ref="drawer"
      size="90%">
      <div class="demo-drawer__content">
        <warning-phone ref="warningPhone" :workPointId="workPointId"></warning-phone>
      </div>
    </el-drawer>
    <!--    监测对象删除-->
    <el-dialog :title="deleteConfirm.name+'监测对象删除确认'" :visible.sync="isDelShowDialog" :close-on-click-modal="false"
               width="220px">
      <div style="text-align: center;color:#ff4d51;margin-bottom: 10px;font-size: 15px">
        警告：监测对象删除后，相关的监测数据将会随之清空！！！
      </div>
      <el-form label-suffix="：" label-position="right" ref="deleteConfirm" :rules="rules" :model="deleteConfirm"
               label-width="0px"
               class="work-point-form">
        <el-form-item prop="mark">
          <el-input v-model="deleteConfirm.mark" placeholder="请输入‘删除’字符，进行确认"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button class="common_btn-white" @click="isDelShowDialog = false">取消</el-button>
        <el-button class="common_btn-defalut" type="primary" @click="validateForm">确定</el-button>
      </span>
    </el-dialog>
    <!-- 监测对象 排序窗口  -->
    <el-dialog title="监测对象排序" :visible.sync="isShowSelectDialog" :close-on-click-modal="false" width="220px">
      <div style="text-align: center;color: #ff4d51;margin-bottom: 10px;font-size: 15px">
        从上至下进行排序，拖拽改变顺序，放至边框边缘进行上下滑动，提交后生效！
      </div>
      <div style="height: 500px;overflow: auto;border: 2px solid #1990FE">
        <el-tree
          :data="workPointSortList"
          node-key="id"
          default-expand-all
          highlight-current
          :allow-drop="allowDrop"
          draggable>
        <span class="custom-tree-node" slot-scope="{ node }">
            <span>
                <i class="el-icon-s-flag" style="margin-right: 10px;color: #1990FE"></i>{{ node.label }}
            </span>
        </span>
        </el-tree>
      </div>

      <span slot="footer" class="dialog-footer">
        <el-button class="common_btn-white" @click="isShowSelectDialog = false">取消</el-button>
        <el-button class="common_btn-defalut" type="primary" @click="sortSubmit">确定</el-button>
      </span>
    </el-dialog>

    <!--    3D上传文件-->
    <el-drawer
      title="3D模型上传"
      :visible.sync="isShowDialog"
      direction="ltr"
      :close-on-click-modal="false"
      custom-class="demo-drawer"
      ref="drawer"
      size="60%">
      <!-- 具体form表单 -->
      <div class="demo-drawer__content" style="margin-top: 30px">
        <el-form label-suffix="：" label-position="right" ref="form" :rules="rules" :model="currentRow"
                 label-width="100px"
                 class="work-point-form">
          <el-row>
            <el-col :span="6">
              <el-form-item prop="width" label="宽度比">
                <el-input v-model="currentRow.width"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item prop="length" label="长度比">
                <el-input v-model="currentRow.length"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item prop="height" label="高度比">
                <el-input v-model="currentRow.height"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item prop="rotate" label="旋转度">
                <el-input v-model="currentRow.rotate"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="8">
              <el-form-item prop="objFile" label-width="110px" label="obj模型文件">
                <upload-file :limit="1" v-model="currentRow.objFile" ref="uploadClearobj"></upload-file>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item prop="mtlFile" label-width="110px" label="mtl模型文件">
                <upload-file :limit="1" v-model="currentRow.mtlFile" ref="uploadClearmtl"></upload-file>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label-width="110px" prop="bmpFile" label="bmp模型文件">
                <upload-file :limit="1" v-model="currentRow.bmpFile" ref="uploadClearbmp"></upload-file>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>
      <!-- 操作按钮 -->
      <div class="demo-drawer__footer">
        <el-button class="common_btn-white" @click="isShowDialog = false">取消</el-button>
        <el-button class="common_btn-defalut" type="primary" @click="validateForm('3D')">确定</el-button>
      </div>
    </el-drawer>
    <x-loading v-show="isLoading"></x-loading>
  </div>
</template>

<script>
  import {getLocalStorageItem} from '@/utils/storage-helper'
  import {
    getWorkPointList,
    workPointDelete,
    workPointModelAddOrUpdate,
    workPointModelQueryByWorkPointId,
    workPointSort,
    workSelect
  } from '@/services/model/project-info'
  import {getDamageSelectList, getSlopeSelectList} from '@/services/model/road-mgmt'
  import {getBridgeqQerySelectList,} from '@/services/model/bridge-info'
  import UploadFile from '@/components/upload-file'

  import Enums from '@/utils/enums'
  import {actions, store} from '../work-point.store'
  import Format from '@/utils/format'
  import WorkPointAddEdit from './dialog-add-edit'
  import MonitorPointAddEdit from '../monitor-point/dialog-add-edit'
  import WarningRules from '@/views/monitor/warning_rules/warning-rules-workpoint'
  import WarningPhone from '@/views/monitor/warning_rules/warning-phone-workpoint'
  import XLoading from '@/components/animation/x-loading.vue'
  import Permission from '@/utils/permission'
  import vueQr from "vue-qr";

  export default {
    mixins:[Enums],
    components: {WorkPointAddEdit, MonitorPointAddEdit, WarningRules, XLoading, UploadFile, WarningPhone,vueQr},
    data() {
      return {
        qrText: '',
        rules: {
          mark: {required: true, message: '请输入‘删除’字符'},
        },
        isShowDialog: false,
        isShowSelectDialog: false,
        EnumWarningLevelList: [],
        workPointId: '',
        workAddId: 1,
        // 接口正在加载
        form: {
          page: 1,
          pageSize: 10,
          name: '',
          monitorType: null,
          projectId: this.$route.params.projectId
        },
        newForm: false,
        newFormPhone: false,
        isLoading: false,
        total: 0,
        tableList: [],
        deleteConfirm: {
          mark: '',
          id: '',
        },
        currentRow: {},
        isDelShowDialog: false,
        // 物质组成
        EnumProjectMonitorTypeList: [],
        slopeList: [],
        damageList: [],
        bridgeList: [],
        selectListDeptTreeId: '',
        selectListRoadId: '',
        workPointSortList: []
      }
    },
    filters: {
      // 时间格式化
      formatTimer(timer) {
        return Format(new Date(timer))
      },
      gradeColor(val) {
        switch (val) {
          case 1:
            return 'background-color:#0DC26B;color:white'
          case 2:
            return 'background-color:#0073b7;color:white'
          case 3:
            return 'background-color:#f39c12;color:white'
          case 4:
            return 'background-color:#ff851b;color:white'
          case 5:
            return 'background-color:#e43321;color:white'
          default:
            return 'background-color:#ffffff;color:white'
        }
      },
      gradeMonitorType(val) {
        let iconMap = {
          1: 'iconshenbuweiyicexieyi',
          2: 'iconGNSS',
          3: 'iconlaxianweiyi',
          4: 'iconjiangyuliang',
          5: 'icondixiashuiwei',
          7: 'iconjinglishuizhunyi2',
          8: 'iconqingjiao',
          9: 'iconxianxingtu',
          10: 'iconshidu',
          11: 'iconfengsufengxiangjiance',
          12: 'icondiyingli',
          13: 'iconzhendong',
          14: 'iconjianshiqicai01',
          15: 'iconGNSS',
          16: 'iconjianshiqicai01',
          17: 'iconzhendong',
          18: 'iconleida',
          19: 'iconshengguangbaojing',
          20: 'icona-fenzu1',
          21: 'iconzhendong',
          22: 'icondb_fill',
          23: 'iconzhendong',
        }
        return iconMap[val]
      },

    },
    computed: {
      projectDetail() {
        return store.projectInfo
      },
    },
    methods: {
      async qrcode(id) {
        this.qrText = 'https://www.jgbpy.com/web/workPointInfo?' + Base64.encode(id)
      },
      async sortSubmit() {
        let name = []
        let i = this.workPointSortList.length
        //更新排序值
        this.workPointSortList.map(x => {
          x.weight = i
          name.push(x)
          i--
        })
        let res = await workPointSort(name)
        if (res.code === 200) {
          this.$notify({
            type: 'success',
            title: '提示',
            message: '排序调整成功！'
          })
          this.isShowDialog = false
          this.queryList()
          this.reFlesh()
        }
      },
      //拖拽时判定目标节点能否被放置。type 参数有三种情况：'prev'、'inner' 和 'next'，分别表示放置在目标节点前、插入至目标节点和放置在目标节点后
      allowDrop(draggingNode, dropNode, type) {
        //限制拖入节点内
        return type !== 'inner'
      },
      //打开排序
      async handleSortWorkPoint() {
        let {data} = await workSelect({id: this.form.projectId})
        this.workPointSortList = data.map(x => {
          return {id: x.id, weight: x.weight, label: x.name}
        })
        this.isShowSelectDialog = true
      },
      handleAdd3d(row) {
        this.currentRow = {}
        this.$nextTick(() => {
          this.$refs.uploadClearbmp.clears()
          this.$refs.uploadClearmtl.clears()
          this.$refs.uploadClearobj.clears()
        })
        this.workPointModelQueryByWorkPointId(row.id)
        this.isShowDialog = true
      },
      async workPointModelQueryByWorkPointId(id) {
        // 查询3d模型
        let res = await workPointModelQueryByWorkPointId({id: id})
        this.currentRow = res.data
        this.currentRow.workPointId = id

      },
      validateForm(name) {
        if (name === '3D') {
          this.$refs.form.validate((valid) => {
            if (valid) {
              this.workPointModelAddOrUpdate()
            }
          })
        } else {
          this.$refs.deleteConfirm.validate((valid) => {
            if (valid) {
              this.submitDelete()
            }
          })
        }

      },
      async workPointModelAddOrUpdate() {
        let res = await workPointModelAddOrUpdate(this.currentRow)
        if (res.code === 200) {
          this.$notify({
            type: 'success',
            title: '提示',
            message: '提交成功'
          })
          this.isShowDialog = false
          this.queryList()
        }
      },
      async submitDelete() {
        let res = await workPointDelete(this.deleteConfirm)
        if (res.code === 200) {
          this.$notify({
            type: 'success',
            title: '提示',
            message: '监测对象删除成功'
          })
          this.reFlesh()
        }
      },
      // 处理删除
      async handleDelete(row) {
        this.isDelShowDialog = true
        this.deleteConfirm = {
          name: row.name,
          mark: '',
          id: row.id,
        }
        this.$nextTick(() => {
          this.$refs.deleteConfirm.clearValidate()
        })
      },
      // 判断权限
      hasPermission(permissionStr) {
        return Permission(this.$store.state.userInfo, permissionStr)
      },
      async getSlopeSelectLists() {
        let projectInfo = getLocalStorageItem("projectInfo")
        if (!projectInfo) {
          return
        }
        // 如果监测项目没有关联管养单位，不查询边坡下拉选项框
        if (!projectInfo.roadId || !projectInfo.deptTreeId) {
          return
        }
        let bridgeBata = await getBridgeqQerySelectList({
          deptTreeId: projectInfo.deptTreeId,
          roadId: projectInfo.roadId
        })
        this.bridgeList = bridgeBata.data
        let {data} = await getDamageSelectList({deptTreeId: projectInfo.deptTreeId, roadId: projectInfo.roadId})
        this.damageList = data
        let res = await getSlopeSelectList({deptTreeId: projectInfo.deptTreeId, roadId: projectInfo.roadId})
        this.slopeList = res.data
      },
      // 分页大小改变
      handleSizeChange(val) {
        this.form.pageSize = val
        this.queryList()
      },
      // 当前页码改变
      handleCurrentChange(val) {
        this.form.page = val
        this.queryList()
      },
      //添加监测点和监测对象时刷新左侧导航菜单
      reFlesh() {
        this.queryList()
        this.isDelShowDialog = false
        let projectId = this.$route.params?.projectId
        actions.queryWorkPointList(projectId)
        actions.queryProjectInfo(projectId)
      },
      // 添加监测点
      handleAddMonitorPoint(row) {
        this.$refs.monitorPoint.handleAdd(row.id)
      },
      // 新增数据
      handleAdd() {
        this.$refs.workPoint.handleAdd()
      },
      handleControl(row) {
        this.newForm = true
        this.workPointId = row.id
        this.$nextTick(function () {
          this.$refs.warningRules.changeWorkPointId(row.id);
        });
      },
      handleControlPhone(row) {
        this.newFormPhone = true
        this.workPointId = row.id
        this.$nextTick(function () {
          this.$refs.warningPhone.changeWorkPointId(row.id);
        });
      },
      /**
       * row  当前操作行的对象
       */
      handleEdit(row) {
        this.$refs.workPoint.handleEdit(row)
      },
      async queryList() {
        this.isLoading = true
        // 查询监测对象列表
        let res = await getWorkPointList(this.form)
        this.tableList = res.data?.records || []
        this.form.page = Number(res.data?.current)
        this.total = Number(res.data?.total)
        this.isLoading = false
      },
      toControl(val, projectId) {
        this.$router.push({
          path: `/project/${projectId}/work-point/${val.workPointId}/monitor/${val.monitorType}`
        })
      },
    },
    created() {

    },
    mounted() {
      // 监测类型
      this.queryDictList(['EnumWarningLevel','EnumProjectMonitorType'], ['EnumWarningLevelList', 'EnumProjectMonitorTypeList'])
      this.getSlopeSelectLists()
    },
    activated() {
      if (this.$route.query.warningLevel) {
        this.form.warningLevel = parseInt(this.$route.query.warningLevel)
      }
      this.queryList()
      // 查询项目信息
      const projectId = this.$route.params?.projectId
      actions.queryProjectInfo(projectId)
    }
  }
</script>
<style scoped="scoped" lang="less">
  @import url('../common');

  .monitor-type {
    color: #2196f3 !important;
    display: inline-block;
    margin-left: 0px;
    margin-right: 0px !important;
    padding: 0px !important;
  }

  .el-date-editor.el-input, .el-date-editor.el-input__inner {
    width: auto;
  }

  .warning_button {
    padding: 0px 5px !important;
    font-size: 12px;
    height: 20px !important;
  }

  .TypeName {
    /deep/ .el-button {
      color: black !important;
    }
  }

  .demo-drawer {

    .demo-drawer__content {
      height: 90%;
    }

    .demo-drawer__footer {
      bottom: 5%;
    }
  }
</style>
